package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class LogClient {

	private static String host = "127.0.0.1";
	private static byte[] addr = {(byte)127, (byte)0, (byte) 0, (byte)1};
	private static int port = 13337;

	public static void main(String[] args) {
		String s;
		if (args.length == 0) {
			String[] bytes = host.split("\\.");
			addr = new byte[4];
			addr[0] = Byte.parseByte(bytes[0]);
			addr[1] = Byte.parseByte(bytes[1]);
			addr[2] = Byte.parseByte(bytes[2]);
			addr[3] = Byte.parseByte(bytes[3]);
		}
		if (args.length == 1 && (!args[0].equals("${port}") || !args[0].equals("${host}"))) {
			host = args[0];
			String[] bytes = host.split("\\.");
			addr = new byte[4];
			addr[0] = Byte.parseByte(bytes[0]);
			addr[1] = Byte.parseByte(bytes[1]);
			addr[2] = Byte.parseByte(bytes[2]);
			addr[3] = Byte.parseByte(bytes[3]);
		}
		if (args.length == 2
				&& !(args[0].equals("${port}") || args[0].equals("${host}") || (args[1]
						.equals("${port}") || args[1].equals("${host}")))) {
			host = args[0];
			String[] bytes = host.split("\\.");
			addr = new byte[4];
			addr[0] = Byte.parseByte(bytes[0]);
			addr[1] = Byte.parseByte(bytes[1]);
			addr[2] = Byte.parseByte(bytes[2]);
			addr[3] = Byte.parseByte(bytes[3]);
			port = Integer.parseInt(args[1]);
		} 
		try {
			InetAddress inet = InetAddress.getByAddress(addr);
			Socket server = new Socket(inet, port);
			System.out.println("Connected to LogServer host "
					+ server.getInetAddress());
			BufferedReader fromServer = new BufferedReader(
					new InputStreamReader(server.getInputStream()));
			PrintWriter toServer = new PrintWriter(server.getOutputStream(),
					true);
			Scanner input = new Scanner(System.in);
			input.useDelimiter("(\\\n)|(\\\r)|(\\\r\\\n)");
			
			s = "";

			while (!s.equals("BYE")) {
				s = input.nextLine(); // This is somewhat flawed since there
				// may be more than one line that the
				// server is broadcast
				toServer.println(s);
			}
			fromServer.close();
			toServer.close();
			input.close();
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
